package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.Product;
import csu.web.mypetstore.service.AccountService;
import csu.web.mypetstore.service.CatalogService;
import csu.web.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/SignOnByPhone")
public class SignOnByPhoneServlet extends HttpServlet {
    private static final String SIGNON_FORM = "/WEB-INF/jsp/account/phonenumsignon.jsp";
    private String phone;
    private String msg;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        phone=req.getParameter("phone");
        AccountService accountService = new AccountService();
        Account loginAccount = accountService.getAccountByPhone(phone);
        if(loginAccount==null){
            this.msg = "No Account Found";
            req.getRequestDispatcher(SIGNON_FORM).forward(req,resp);
        }else{
            HttpSession session = req.getSession();
            session.setAttribute("loginAccount",loginAccount);

            if(loginAccount.isListOption()){
                CatalogService catalogService = new CatalogService();
                List<Product> myList = catalogService.getProductListByCategory(loginAccount.getFavouriteCategoryId());
                session.setAttribute("myList",myList);
            }

            resp.sendRedirect("MainForm");
        }
    }
}
